import { _decorator, assetManager, ImageAsset, Node, resources, Toggle, tween, UITransform, v3 } from 'cc';
import { EDITOR } from 'cc/env';
import {
    ccclass,
    ccmodifier,
    executeInEditMode,
    HTMLRichText,
    property,
} from '../../../extensions/cc-feather/assets/src';

/**
 * - 作者: DoooReyn
 * - 日期: 2023.11.17
 * - 名称: HTMLRichTextDemo
 * - 描述: HTML 超级富文本示例
 */
@ccclass
@ccmodifier('HTMLRichTextDemo')
@executeInEditMode(true)
export class HTMLRichTextDemo extends HTMLRichText {
    @property(Node)
    placeholder: Node;

    @property(Toggle)
    toggle: Toggle;

    onToggle() {
        this.debugDraw = this.toggle.isChecked;
    }

    protected start() {
        /** 开发者使用时，需要先将用到的图片资源加载进来 */
        if (EDITOR) {
            // 编辑器模式下可以通过 UUID 来获取图片资源
            const uuid = '99ce2773-c288-4d67-9868-27bb8d5e9ea9';
            assetManager.loadAny<ImageAsset>(uuid, (err: Error) => {
                if (err) return console.error(err);
                super.start();
            });
        } else {
            resources.load('image/gold', ImageAsset, (err: Error) => {
                if (err) return console.error(err);
                super.start();
            });
        }
    }

    /**
     * 插入自定义节点回调
     * @param x 起始点 X
     * @param y 起始点 Y
     * @param rowHeight 当前行的高度
     * @param size 节点的尺寸
     */
    private insertCustomNode(x: number, y: number, rowHeight: number, size: [number, number]) {
        const { width, height } = this._canvas;
        const [left, top] = this._parser.style.margin;
        const [cw, ch] = size;
        let offset = { x: -width / 2, y: -height / 2 };
        let origin = { x: x + left, y: height - y - top };
        let transform = this.placeholder.getComponent(UITransform)!;
        let { width: pw, height: ph } = transform;
        let { x: ax, y: ay } = transform.anchorPoint;
        let pos = {
            x: origin.x + offset.x + cw / 2 + (0.5 - ax) * pw,
            y: origin.y + offset.y + ch / 2 + (0.5 - ay) * ph - 87,
        };
        this.placeholder.setPosition(pos.x, pos.y, 0);
        this.placeholder.setScale(0.5, 0.5, 1);
    }
}
